import axios from 'axios'
import { getBaseURL, getReqSign } from '@/utils/index'
import { isDev } from '@/utils/env'
import config from '@/config'
import { message } from 'antd'

const instance = axios.create({
  baseURL: getBaseURL(),
  timeout: 100000
})

//请求拦截器
instance.interceptors.request.use(
  (config) => {
    config.headers['Sign'] = getReqSign()
    // const useStore = useUserStore()    
    // if (useStore.token) {
    //   config.headers['Authorization'] = `Bearer ` +useStore.token
    // }
    return config
  },
  (err) => Promise.reject(err)
)

//响应拦截器
instance.interceptors.response.use(
  (response) => {
    // const userStore = useUserStore()
    const res = response.data
    const code = res[config.statusName]
    if (config.successCode.includes(code)) {
      return res
    } else {
      if (code == 400) {
        message.error(res[config.messageName])
      }
      // else if (code === 410000 || code === 50012 || code === 50014) {
      //   if (isDev()) {
      //     message.error(res[config.messageName])
      //     alert('跳登录页面')
      //   } else {
      //     // userStore.removeAll()
      //     location.href = '/'
      //   }
      //   return
      // }
    }
    return Promise.reject(res)
  },
  (err) => {
    message.error(err.message || '服务器异常')
    return Promise.reject(err)
  }
)

export default instance
